package com.gnerv.rabbitmq.agent.service;

import com.gnerv.rabbitmq.agent.cache.ClusterCache;
import com.gnerv.rabbitmq.agent.cache.NodeCache;
import com.gnerv.rabbitmq.agent.model.entity.ClusterStatus;
import com.gnerv.rabbitmq.agent.model.entity.NodeStatus;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author Gnerv LiGen
 */
@Service
public class ClusterService {

    public List<NodeStatus> listNodeStatus(String clusterName) {
        ClusterStatus clusterStatus = ClusterCache.STATUS.getIfPresent(clusterName);
        if (ObjectUtils.isEmpty(clusterStatus)) {
            throw new RuntimeException("无法获取[ " + clusterName + " ]集群状态");
        }
        List<NodeStatus> nodeStatusList = Lists.newArrayList();
        nodeStatusList .addAll(listDiscNode(clusterStatus));
        nodeStatusList .addAll(listRamNode(clusterStatus));
        return nodeStatusList;
    }

    public List<NodeStatus> listDiscNode(ClusterStatus clusterStatus) {
        List<NodeStatus> nodeStatusList = Lists.newArrayList();
        List<String> discList = clusterStatus.getDisc();
        for (String disc : discList) {
            NodeStatus nodeStatus = NodeCache.STATUS.getIfPresent(disc);
            if (ObjectUtils.isEmpty(nodeStatus)) {
                nodeStatus = new NodeStatus();
            }
            nodeStatus.setType("disc");
            if (clusterStatus.getRunning().contains(disc)) {
                nodeStatus.setStatus("running");
            } else {
                nodeStatus.setStatus("stopped");
            }
            nodeStatusList.add(nodeStatus);
        }
        return nodeStatusList;
    }


    public List<NodeStatus> listRamNode(ClusterStatus clusterStatus) {
        List<NodeStatus> nodeStatusList = Lists.newArrayList();
        List<String> ramList = clusterStatus.getRam();
        for (String ram : ramList) {
            NodeStatus nodeStatus = NodeCache.STATUS.getIfPresent(ram);
            if (ObjectUtils.isEmpty(nodeStatus)) {
                nodeStatus = new NodeStatus();
            }
            nodeStatus.setType("ram");
            if (clusterStatus.getRunning().contains(ram)) {
                nodeStatus.setStatus("running");
            } else {
                nodeStatus.setStatus("stopped");
            }
            nodeStatusList.add(nodeStatus);
        }
        return nodeStatusList;
    }

}
